package cn.sibu.plugin.authorize.activity;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.sibu.plugin.authorize.R;
import cn.sibu.plugin.authorize.bean.CheckdeCodeEvent;
import cn.sibu.plugin.authorize.bean.SendDentifyingCodeEvent;
import cn.sibu.plugin.authorize.bean.UserInfo;
import cn.sibu.plugin.authorize.http.SibuAuthorizeHttp;
import cn.sibu.plugin.authorize.util.ActivityLifeCycle;
import cn.sibu.plugin.authorize.util.ButtonAvoidForceUtils;
import cn.sibu.plugin.authorize.util.ConfigKeyName;
import cn.sibu.plugin.authorize.util.DialogUtil;
import cn.sibu.plugin.authorize.util.ErrorContent;
import cn.sibu.plugin.authorize.util.L;
import cn.sibu.plugin.authorize.util.RequestParamName;
import cn.sibu.plugin.authorize.util.ResponseCode;
import cn.sibu.plugin.authorize.util.SharedPreferencesUitls;
import cn.sibu.plugin.authorize.view.EditTextWithDelete;
import core.dl.internal.DLIntent;
import de.greenrobot.event.EventBus;

/**
 *TODO  验证码处理类 处理登录验证码和修改密码验证码
 * @data:  2015-2-3 上午10:02:55 
 * @version:  V1.0
 */
public class AuthcodeActivity extends BaseActivity implements OnClickListener{
	public static final String CODETYPE="codetype";



	// 提交验证码
		@InjectView(R.id.bt_authcodelogin_confirm)
		Button bt_authcodelogin_confirm;

		// 请求验证码
		@InjectView(R.id.bt_authcode_send)
		Button bt_authcode_send;

		// 返回登录首页
		@InjectView(R.id.btn_backlogin)
		Button btn_backlogin;

		// 倒计时的时间
		private int recLen = 60;
		// 验证码产生的时间
		private long starttime;
		// 获取的验证码
		private String code;
		// 短信验证码id
		private String mcid;

		// 提示显示
		@InjectView(R.id.ll_tv_tishi)
		LinearLayout ll_tv_tishi;

		// 验证码
		@InjectView(R.id.et_authcode_login)
		EditTextWithDelete et_authcode_login;

		// 已发送的手机号
		@InjectView(R.id.tv_authcode_phonenum)
		TextView tv_authcode_phonenum;

		String mobile;


		
		// 是否获取验证码
	 	private boolean is_obtain = false;
	 	
	 	private String mcode;

		private  String type;//请求验证码的类型
	
	 @Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
		 setContentView(R.layout.activity_authcode_login);
		 ButterKnife.inject(this);
		 EventBus.getDefault().register(this);
		 initUI();
		 //得到手机号
		 mobile = getIntent().getStringExtra("mobile");
		 //得到请求意图
		 type=getIntent().getStringExtra(CODETYPE);

	}
//	public void onDestroy(){
//		EventBus.getDefault().unregister(this);
//		super.onDestroy();
//	}
	 public void initUI() {
			bt_authcode_send.setOnClickListener(this);
			bt_authcodelogin_confirm.setOnClickListener(this);
			btn_backlogin.setOnClickListener(this);
	 }

	 @Override
	public void onClick(View v) {
				switch (v.getId()) {
				// 发送验证码
				case R.id.bt_authcode_send:
					// 刷新UI
					// 倒计时
					bt_authcode_send
							.setBackgroundResource(R.drawable.verify_reciprocal_btn);
					bt_authcode_send.setText(ErrorContent.RESENDAUTNCODE + "("
							+ recLen + "秒" + ")");
					bt_authcode_send.setClickable(false);
					handler.postDelayed(runnable, 1000);
					//网络请求短信验证码
					SibuAuthorizeHttp.sendDentifyingCode(mobile,type,that);

					break;
		// 提交验证码
		case R.id.bt_authcodelogin_confirm:
			//防暴力点击
			if (ButtonAvoidForceUtils.filter()) {
				// 隐藏软键盘
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(
						bt_authcodelogin_confirm.getWindowToken(), Toast.LENGTH_SHORT);

				mcode = et_authcode_login.getText().toString().trim();
				if (is_obtain) {
					if (!TextUtils.isEmpty(mcode)) {
						bt_authcodelogin_confirm.setClickable(false);
						//缓冲效果
						DialogUtil.showDialogForLoading(that, "正在加载...", true);
						// 提交验证码
						SibuAuthorizeHttp.checkCode(mobile,type,mcode,that);
					} else {
						Toast.makeText(that,
								ErrorContent.AUTHCODENULL, Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(that,
							ErrorContent.NOGETAUTHCODE, Toast.LENGTH_SHORT).show();
				}
			}
			break;
				case R.id.btn_backlogin:
					// 返回登录界面
					backLoginUI();
					break;
				}
			 
	 }

	/**
	 * 提交验证码的回调
	 * @param event
	 */
	public void  onEventMainThread(CheckdeCodeEvent event){
		DialogUtil.dismissDialogForLoading();
		bt_authcodelogin_confirm.setClickable(true);
		if(ResponseCode.SUCCEED.equals(event.code)){//成功

			//根据type分辨是和意图
			if(RequestParamName.LOGIN_AUTHCODE.equals(type)){//登录意图
				UserInfo userInfo=event.getUser();
				EventBus.getDefault().postSticky(userInfo);//发送粘性用户信息数据
				//保存用户数据到本地，下次免登录时使用
				String userInfoJson=JSON.toJSONString(userInfo);
				SharedPreferencesUitls.saveString(that, ConfigKeyName.USERINFO, userInfoJson);
				L.e("登录验证通过");
				//跳转到主界面

				DLIntent mainIntent = new DLIntent(getPackageName(),
						MainActivity.class);
				mainIntent.putExtra(ConfigKeyName.GROUPID, event.user.groupid);
				//主界面是唯一性界面，先移除其他所有界面在跳入到主界面
				ActivityLifeCycle.removeAllActivity();
				startPluginActivity(mainIntent);
				finish();
					//聊天
	//			ChatForbiddenEvent.getAllowChatList2(uid, token);
			}else if(RequestParamName.FORGETPWD_AUTHCODE.equals(type)){//忘记密码意图

			}
		}else{
			Toast.makeText(that,
					ErrorContent.NETERR, Toast.LENGTH_SHORT).show();
		}
	}
	/**
	 * 接受请求验证码的回调
	 * @param event
	 */
		public void onEventMainThread(SendDentifyingCodeEvent event){
			if(ResponseCode.SUCCEED.equals(event.code)){//请求成功
				is_obtain = true;//标志验证码请求成功了
				ll_tv_tishi.setVisibility(View.VISIBLE);
				String phone = mobile;
				phone=phone.substring(0,3)+"****"+phone.substring(7);
				tv_authcode_phonenum.setText(phone);
			}else if(event.code==null){
				Toast.makeText(that,"连接失败",Toast.LENGTH_SHORT).show();
			}
		}
	// 利用handler延时发送，达到倒计时效果
		Handler handler = new Handler();
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				recLen--;
				if (recLen <= 0) {
					recLen = 60;
					bt_authcode_send.setText(ErrorContent.RESENDAUTNCODE);
					bt_authcode_send
							.setBackgroundResource(R.drawable.token_auth_btn_on);
					bt_authcode_send.setClickable(true);
				} else {
					bt_authcode_send.setText(ErrorContent.RESENDAUTNCODE + "("
							+ recLen + "秒" + ")");
					handler.postDelayed(this, 1000);
				}
			}
		};
		
		
		 
}
